/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.rate.point.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.springblade.common.enums.rate.RoleTypeEnum;
import org.springblade.common.enums.rate.YesNoEnum;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.rate.point.entity.PointRecord;
import org.springblade.modules.rate.point.excel.PointRecordExcel;
import org.springblade.modules.rate.point.vo.PointRankVO;
import org.springblade.modules.rate.point.vo.PointRecordVO;
import org.springblade.modules.rate.point.mapper.PointRecordMapper;
import org.springblade.modules.rate.point.service.IPointRecordService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.rate.point.vo.PointStatVO;
import org.springblade.modules.rate.point.vo.req.PointRankReqVO;
import org.springblade.modules.rate.point.vo.req.PointStatReqVO;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 积分记录表 服务实现类
 *
 * @author Blade
 * @since 2021-09-20
 */
@Service
public class PointRecordServiceImpl extends BaseServiceImpl<PointRecordMapper, PointRecord> implements IPointRecordService {

	@Autowired
	private ITenantService tenantService;
	@Autowired
	@Lazy
	private IUserService userService;
	@Autowired
	@Lazy
	private IDeptService deptService;
	@Override
	public IPage<PointRecordVO> selectPointRecordPage(IPage<PointRecordVO> page, PointRecordVO pointRecord) {
		return page.setRecords(baseMapper.selectPointRecordPage(page, pointRecord));
	}

	@Override
	public PointStatVO stat(PointStatReqVO statReqVO) {
		boolean leaderFlag = false;
		BladeUser authUser = AuthUtil.getUser();
			User user = userService.getById(authUser.getUserId());
		if (user.getLeaderFlag()== YesNoEnum.YES.getKey()) {
			leaderFlag = true;
		}
		statReqVO.setMemberId(user.getId());
		PointStatVO pointStatVO = baseMapper.stat(statReqVO);
		return pointStatVO;
	}

	@Override
	public List<PointRankVO> rank(PointRankReqVO rankVO) {
		return baseMapper.rank(rankVO);
	}

	/**
	 * 我的
	 *
	 * @param rankVO
	 */
	@Override
	public PointRankVO myRank(PointRankReqVO rankVO) {
		boolean leaderFlag = false;
		BladeUser authUser = AuthUtil.getUser();
			User user = userService.getById(authUser.getUserId());
		if (user.getLeaderFlag()==YesNoEnum.YES.getKey()) {
			leaderFlag = true;
		}
		PointRankVO myRankVO = new PointRankVO();
		List<PointRankVO> rankVOList =  baseMapper.rank(rankVO);
		for (int i = 0; i < rankVOList.size(); i++) {
			PointRankVO pointRankVO = rankVOList.get(i);
			if (pointRankVO.getMemberId().equals(user.getId())){
				myRankVO = pointRankVO;
				myRankVO.setRank(i+1);
				break;
			}
		}
		return myRankVO;
	}

	/**
	 * 兑换礼物
	 * @param pointRecord
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean exchangeGift(PointRecord pointRecord) {
		try {
			boolean leaderFlag = false;
			BladeUser authUser = AuthUtil.getUser();
			User user = userService.getById(authUser.getUserId());
			if (user.getLeaderFlag()==YesNoEnum.YES.getKey()) {
				leaderFlag = true;
			}
			this.saveOrUpdate(pointRecord);

			//礼物减少

		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException("兑换礼物失败");
		}
		return true;
	}
	/**
	 * 积分当月重置领导
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean resetCurrentMouthQuota(Dept dept,Integer deltaQuota) {
		try {
			//遍历用户
			User uq = new User();
			uq.setTenantId(dept.getTenantId());
			uq.setDeptId(dept.getId().toString());
			List<User> userList = userService.list(Condition.getQueryWrapper(uq));
			for (int j = 0; j < userList.size(); j++) {
				User user = userList.get(j);
				if (user.getLeaderFlag()==YesNoEnum.YES.getKey()) {
					//先查部门
					if (deltaQuota!=null) {
						user.setMouthQuota(user.getMouthQuota() + deltaQuota);
					}
					userService.updateById(user);


				}
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException("积分当月重置领导失败");
		}
		return true;
	}
	/**
	 * 积分每个月重置
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean resetMouthQuota() {

		try {
			log.warn(String.format("积分每个月重置,%s", DateUtil.format(new Date(),DateUtil.PATTERN_DATETIME)));
			List<Tenant> tenantList = tenantService.list();
			for (int i = 0; i < tenantList.size(); i++) {
				Tenant tenant = tenantList.get(i);
				//遍历用户
				User uq = new User();
				uq.setTenantId(tenant.getTenantId());
				List<User> userList = userService.list(Condition.getQueryWrapper(uq));
				for (int j = 0; j < userList.size(); j++) {
					User user = userList.get(j);
					if (user.getLeaderFlag()==YesNoEnum.YES.getKey()) {
						//先查部门
						Dept dept = deptService.getById(user.getDeptId());
						if (dept!=null && dept.getMouthQuota()!=null) {
							user.setMouthQuota(dept.getMouthQuota());
						}else {
							//再查租户
							user.setMouthQuota(tenant.getLeaderQuota());
						}


					}else if (user.getRoleId().equals(RoleTypeEnum.MATE.getRoleId())) {
						user.setMouthQuota(tenant.getMateQuota());
					}
					userService.updateById(user);
				}
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException("积分每个月重置失败");
		}
		return true;
	}

	/**
	 * 导出
	 *
	 * @param queryWrapper
	 */
	@Override
	public List<PointRecordExcel> export(Wrapper<PointRecord> queryWrapper) {
		List<PointRecord> pointRecordList = baseMapper.selectList(queryWrapper);
		List<PointRecordExcel> pointRecordExcels = new ArrayList<>();
		for (int i = 0; i < pointRecordList.size(); i++) {
			PointRecord pointRecord = pointRecordList.get(i);
			PointRecordExcel pointRecordExcel = new PointRecordExcel();
			BeanUtil.copyNonNull(pointRecord,pointRecordExcel);
			pointRecordExcels.add(pointRecordExcel);
		}
		return pointRecordExcels;
	}
}
